package com.inspur.cmp.jov.vjj;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.inspur.cmp.jov.keycloak.tools.CertManager;

public class JavaJwtDemo {
    public static void main(String[] args) {
        CertManager certManager = new CertManager("https://10.7.20.60", "master");

        String token = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJuOHd5MWlkb0JMMk9SX1FHNVNHNjVQZXA1YkZ0cGQ1R0FuVVFtOGh5SDBNIn0.eyJleHAiOjE2NzAzMTU4MzksImlhdCI6MTY3MDMxNTc3OSwianRpIjoiM2U1MzhjZDAtNjMwNS00NzhkLThmMzgtYzEwZjg2OGY4ZGRiIiwiaXNzIjoiaHR0cHM6Ly8xMC43LjIwLjYwL2F1dGgvcmVhbG1zL21hc3RlciIsInN1YiI6IjhhODdhMWY4M2M5MzM3M2IwMTNjOTM0N2IzN2IwMDAwIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYWRtaW4tY2xpIiwic2Vzc2lvbl9zdGF0ZSI6ImUyMzJmNGJlLWFiYTItNDBkNy1iMDE1LTFmMDc1MzBlZTIzNCIsImFjciI6IjEiLCJzY29wZSI6ImluY2xvdWRvcy1zY29wZSBlbWFpbCBwcm9maWxlIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJpbmNsb3Vkb3Mtcm9sZSI6Ilt7XCJyZWdpb25JZFwiOlwicmVnaW9uT25lXCIsXCJyb2xlTGlzdFwiOlt7XCJkb21haW5JZFwiOlwiZG9tYWluaWRcIixcInJvbGVJZFwiOlwidmRjQWRtaW5Sb2xlSWRcIixcInJvbGVUeXBlXCI6XCIyXCIsXCJ2ZGNJZFwiOlwiMVwifSx7XCJkb21haW5JZFwiOlwiXCIsXCJyb2xlSWRcIjpcImFkbWluUm9sZUlkXCIsXCJyb2xlVHlwZVwiOlwiMFwiLFwic3ViUm9sZVR5cGVcIjpcIjBcIixcInZkY0lkXCI6XCJcIn1dfSx7fV0iLCJuYW1lIjoiaW5jbG91ZCIsInByZWZlcnJlZF91c2VybmFtZSI6ImluY2xvdWQiLCJnaXZlbl9uYW1lIjoiaW5jbG91ZDYiLCJsb2NhbGUiOiJ6aCIsImVtYWlsIjoidnZ2djgzMS0xMDAwQGEuY29tIn0.MhDXLHiiO3IGEBbRFcIkp4kkOjjywI7phDJA0mgdqLV_Kjnc2hnNr5KD1wYFfi6RIe82aNZcgKHjcdBqRuF_9CzQHoSmRgnj8s0mzSEDgtTm0Dy3kiHt6Up1PXJMkikjkcelVjJdNDaEkiUwQUGKPqnSXf6aQbFPDu1J-uZtlTDKw2fhDL3BdeiFnGUT2kIJxJP7_oiH7tuUVZAxZL1XK9xnxu_ujj2l_vGlUZMKeC5ouL1jedqdjPdGA6n03I93hmBA0XiWCEe5-jwjtV7Zn88BUPv5Pt1cUiqpKGbvpGrd1VL9PrU6DTMv8SIk0W1gqcnVH8uW0lP_D_JrHbK5vw";

        try {
            validateAccessToken(token,certManager);
        } catch (Exception e) {
            System.err.println("token 验证失败："+e.getMessage());
        }

    }

    public static void validateAccessToken(String accessToken, CertManager certManager) {
        DecodedJWT decodedJWT = JWT.decode(accessToken);

        // get kid
        String keyId = decodedJWT.getKeyId();

        JWT.require(Algorithm.RSA256(certManager.getPublicKey(keyId), null))
                .acceptLeeway(5) // 默认token宽容时间窗口，包括iat,exp,nbf,可以单独配置
                .build()
                .verify(decodedJWT);
    }
}
